<?php

/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2019/3/27
 * Time: 09:33
 */
namespace app\common\lib;

class Socket
{
    private $address= '';
    private $timeout = 5;
    function __construct($address,$timeout)
    {
        $this->address = $address;
        $this->timeout = $timeout;
    }

    /**
     * 异步任务·投递·
     * @param array $array
     * @return string
     */
    public function asyncTask($array=[]){
        $socket = stream_socket_client($this->address, $errno, $errmsg, $this->timeout);
        if(!$socket){
            echo $errmsg;
        }
        $mail_data = $array;
        // 注意，Text协议后面"\n"换行符是必须的
        $mail_buffer = json_encode($mail_data)."\n";
        // 发送给mail worker
        fwrite($socket, $mail_buffer);
        $result = fread($socket, 4);
        fclose($socket);
        if ($result != 'ok'){
            return 'error';
        }
        return 'success';
    }

}